'use strict'

const { personalDetails } = require('../models');

// 个人信息控制器

// 个人信息页面
var fn_personalDetails = async (ctx, next) => {
    // 用户名
    var username = ctx.session.userName;
    var userId = ctx.session.userId;

    // 获取数据库关于当前用户的个人信息
    var currentUserMsg = JSON.parse(JSON.stringify( await personalDetails.findOne({
        where: {
            userId: userId
        }
    })));
    console.log(currentUserMsg);
    // 性别
    var sex = currentUserMsg.sex === null ? "未知" : currentUserMsg.sex;
    //手机号码
    var phoneNumber = currentUserMsg.phoneNumber === null ? "暂无" : currentUserMsg.phoneNumber;
    //兴趣爱好
    var interest = currentUserMsg.interest === null ? "暂无" : currentUserMsg.interest;
    //个人简介
    var individualResume = currentUserMsg.individualResume === null ? "暂无" : currentUserMsg.individualResume;

    // console.log(phoneNumber);

    var obj = {
        username,
        sex,
        phoneNumber,
        interest,
        individualResume
    }

    ctx.render('personalDetails.html', obj)
};

// 编辑个人信息页面
var fn_editPersonalDetails = async (ctx, next) => {
    // 用户名
    var userName = ctx.session.userName;

    var obj = {
        userName
    }
    ctx.render('editPersonalDetails.html', obj)
};

// 判断编辑个人信息是否有错误
var fn_personalDetailsJudge = async (ctx, next) => {
    // 将数据库需要的字段保存进去（暂时不给条件）
    //用户Id
    var userId = ctx.session.userId;
    //性别
    var sex = ctx.request.body.sex.trim();
    //兴趣
    var interest = ctx.request.body.interest.trim();
    //个人简介
    var individualResume = ctx.request.body.individualResume.trim();
    //电话号码
    var phoneNumber = ctx.request.body.phoneNumber.trim();

    // console.log(userId);
    // console.log(sex);
    // console.log(individualResume);

    // 个人信息表中是否存在当前用户
    var currentUser = await personalDetails.findOne({
        where: {
            id: userId
        }
    });
    // console.log(currentUser);

    if (currentUser === null) {
        //如果没有该用户则创建
        await personalDetails.create({
            userId: userId,
            sex: sex,
            interest: interest,
            individualResume: individualResume,
            phoneNumber: phoneNumber
        });
    } else {
        //如果有该用户则更新
        await personalDetails.update({
            sex: sex,
            interest: interest,
            individualResume: individualResume,
            phoneNumber: phoneNumber
        }, {
            where: {
                id: userId
            }

        });
    }





    let res = "";
    res = { code: 200, msg: "保存个人信息成功" };
    ctx.body = JSON.stringify(res);
}


module.exports = {
    '/home/personalDetails': ['get', fn_personalDetails],
    '/home/editPersonalDetails': ['get', fn_editPersonalDetails],
    '/home/personalDetailsJudge': ['post', fn_personalDetailsJudge],
}